import sqlite3
from cliMW_ui import Ui_MainWindow
from PySide6.QtWidgets import QApplication, QTableWidgetItem, QMainWindow
import sys

# 每次要手动修改selectionmode为singleSelection 和behavior为rows


class myCli(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mw = Ui_MainWindow()
        self.mw.setupUi(self)
        self.conn = sqlite3.connect("test.db")
        self.cursor = self.conn.cursor()
        self.bind()

    def bind(self):
        self.mw.searchBtn.clicked.connect(self.search)

    def search(self):
        if self.mw.paf.currentText() == "自研":
            self.model = "ngsf"
        else:
            self.model = "other"
        sqlSearchMid = self.mw.cliInput.text()
        if (sqlSearchMid.strip() == ""):
            return
        sqlSearchMid = sqlSearchMid.replace(" ", "*")
        sqlSearchStart = "select * from CliSearch where model='" + \
            self.model + "' and cmd glob '*"   # 这里一定要加'不然对于sqlite3来说语句不正确。
        sqlSearchEnd = "*'"
        sqlStrAll = sqlSearchStart + sqlSearchMid + sqlSearchEnd
        self.cursor.execute(sqlStrAll)
        data = self.cursor.fetchall()
        self.resShow(data)

    def resShow(self, data: list):
        length = len(data)
        self.mw.statusbar.showMessage("找到"+str(length)+"条记录")
        self.mw.tblShow.setRowCount(length)
        for i in range(length):
            for j in range(2):  # 只加入mid和cmd两个元素
                self.mw.tblShow.setItem(i, j, QTableWidgetItem(
                    str(data[i][j])))  # 必须转换为str才能加入内容


if __name__ == "__main__":

    app = QApplication(sys.argv)
    mainWindow = myCli()
    mainWindow.show()
    sys.exit(app.exec())
